package com.aaa.tars.service.impl;

import com.aaa.tars.dao.RoleDao;
import com.aaa.tars.entity.Menu;
import com.aaa.tars.entity.Role;
import com.aaa.tars.entity.User;
import com.aaa.tars.service.RoleService;
import com.aaa.tars.util.CustomException;
import com.aaa.tars.util.Page;
import com.aaa.tars.util.ResultStatus;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @FileName: RoleServiceImpl
 * @Description:
 * @Author: xm
 * @CreateTime: 2025/9/8 21:17
 * @Version: 1.0.0
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleDao roleDao;

    @Resource
    private HttpSession session;

    @Override
    public List<Role> queryAll() {
        return roleDao.queryAll();
    }

    @Override
    public PageInfo queryByPage(Page<Role> page) {
        Integer pageNo = page.getPageNo();
        Integer pageSize = page.getPageSize();

        if(pageNo==null||pageNo==0||pageSize==null||pageSize==0){
            throw  new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(),ResultStatus.PARAM_ISNULL.getStatusMessage());
        }
        PageHelper.startPage(pageNo,pageSize);
        Role role = page.getData();
        List<Role> studentList = roleDao.queryAllByLimit(role);
        return new PageInfo(studentList);
    }

    @Override
    public Role queryById(Integer roleId) {
        if(roleId==null||roleId<0){
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(),ResultStatus.PARAM_ISNULL.getStatusMessage());
        }
        return roleDao.queryById(roleId);
    }

    @Override
    public int insert(Role role) {
        // 设置账号状态
        role.setStatus("0");
        // 设置账号删除标识
        role.setDelFlag("0");
        //动态获取创建人
        //拿到登录session
        User userInfo = (User) session.getAttribute("userInfo");
        role.setCreateBy(userInfo.getUserName());

        // 创建角色时设置本地时间
        role.setCreateTime(LocalDateTime.now());
        return roleDao.insert(role);
    }

    @Override
    public int update(Role role) {
        //动态获取创建人
        //拿到登录session
        User userInfo = (User) session.getAttribute("userInfo");
        role.setUpdateBy(userInfo.getUserName());
        // 设置更新时间
        role.setUpdateTime(LocalDateTime.now());
        return roleDao.update(role);
    }

    @Override
    public int deleteById(Integer roleId) {
        if(roleId==null||roleId<0){
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(),ResultStatus.PARAM_ISNULL.getStatusMessage());
        }
        //用户名为111，删除失败
        if ("admin".equals(this.queryById(roleId).getRoleKey())) {
            throw new CustomException(1031,"不能删除超级管理员");
        }
        return roleDao.deleteById(roleId);
    }

    @Override
    public List<Role> queryByRoleName(String roleName) {
        Role role = new Role();
        role.setRoleName(roleName);
        return roleDao.queryAllByLimit(role);
    }

    //获取角色权限
    @Override
    public List<Menu> getMenusByRoleId(Integer roleId) {
        // 查询数据库，若无结果返回空列表
        List<Menu> menus = roleDao.selectMenusByRoleId(roleId);
        return menus != null ? menus : new ArrayList<>();
    }

    @Override
    public void assignMenus(Integer roleId, List<Integer> menuIds) {
        if (roleId == null || roleId <= 0) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "角色ID无效");
        }

        System.out.println("=============================================");
        System.out.println("service外授权Id:=============="+menuIds);
        System.out.println("=============================================");


        // 先删除旧的关联
        roleDao.deleteRoleMenu(roleId); // 清空所有角色


        if (menuIds != null && !menuIds.isEmpty()) {
            for (Integer menuId : menuIds) {
                if (menuId != null && menuId > 0) {
                    System.out.println("=============================================");
                    System.out.println("内插入授权Id:=============="+menuId);
                    System.out.println("=============================================");
                    roleDao.insertRoleMenu(roleId, menuId);
                }
            }
        }

    }
}
